package com.app.teadoor.login;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.teadoor.bean.BasisBean;
import com.app.teadoor.bean.LoginBean;
import com.app.teadoor.bean.LoginServiceListData;
import com.app.teadoor.home.HomeTabActivity;
import com.app.teadoor.R;
import com.app.teadoor.basis.BasisActivity;
import com.app.teadoor.basis.Constants;
import com.app.teadoor.util.MyUtils;
import com.flyco.dialog.listener.OnBtnClickL;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import my.ActivityTool;
import my.DialogUtils;
import my.IntentUtils;
import my.LogUtil;
import my.MySharedPreferences;
import my.http.MyHttpUtils;
import my.http.MyHttpListener;
import my.http.MyParams;

public class LoginActivity extends BasisActivity {


    @BindView(R.id.eidt_user)
    EditText eidt_user;
    @BindView(R.id.edit_pwd)
    EditText edit_pwd;


    public static void ToLogin(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivityForResult(intent, requestCode);

    }


    public static void toLoginAllClear(Context mContext) {
        LoginBean.logout();
        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    public static void toLoadingAllClearNologout(Context mContext) {
        Intent intent = new Intent(mContext, HomeTabActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    public static boolean toLoginIfNotLoginDialog(final Activity context, final int requestCode) {
        if (!LoginBean.isLogin()) {
            DialogUtils.DialogTwo(context, "", "您未登录，是否立即登录？", "立即登录", "取消", new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    ToLogin(context, requestCode);
                }
            }, null);

            return false;
        }
        return true;

    }

    public static void ToLogin(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);

    }

    @Override
    public void initViews() {
        super.initViews();
        setDefautTrans(false);
        setContentView(R.layout.login_activity);
        setTitleBg(R.color.transparent);
        QMUIStatusBarHelper.translucent(mContext);
        QMUIStatusBarHelper.setStatusBarLightMode(mContext);

        setTitle("");
        edit_pwd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_GO) {
                    findViewById(R.id.btn_login).performClick();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        LoginBean.logout();
        setCheckView();

        Acp.getInstance(this).request(new AcpOptions.Builder()
                        .setPermissions(Manifest.permission.INTERNET
                                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                                , Manifest.permission.READ_EXTERNAL_STORAGE
                                , Manifest.permission.ACCESS_COARSE_LOCATION
                                , Manifest.permission.ACCESS_FINE_LOCATION
                                , Manifest.permission.ACCESS_WIFI_STATE
                                , Manifest.permission.READ_PHONE_STATE
                                ,Manifest.permission.CAMERA
                                , Manifest.permission.ACCESS_WIFI_STATE
                                , Manifest.permission.CALL_PHONE
                                ,Manifest.permission.READ_CONTACTS
                                ,Manifest.permission.WRITE_CONTACTS
                                ,Manifest.permission.READ_SMS
                        ).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        initReal();
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
//                        BasisApp.showToast(permissions.toString() + "权限拒绝");
                        DialogUtils.DialogOKmsgFinish(mContext, "拒绝权限，结束程序");
                    }
                });

    }

    void initReal() {
        MySharedPreferences msp = new MySharedPreferences(mContext);
        if (msp.getRememberPwd()) {
            eidt_user.setText(msp.getUser());
        }
        if (msp.getRememberPwd()) {
            edit_pwd.setText(msp.getPassword());
        }


        LoginServiceListData loginServiceListData = LoginServiceListData.getFromCache();
        if(loginServiceListData == null){
            loginServiceListData = new LoginServiceListData();
            loginServiceListData.setIp(SeverSettingActivity.getSeverDefaultListBean().getList().get(0).getId());
            loginServiceListData.save();
        }else {
            if(!TextUtils.isEmpty(loginServiceListData.getIp()) && loginServiceListData.getIp().endsWith("/serv")){
                loginServiceListData.setIp(loginServiceListData.getIp().substring(0,loginServiceListData.getIp().lastIndexOf("/serv")));
                loginServiceListData.save();
                MyUtils.putSerciceData(loginServiceListData);
            }
        }

        if (LoginServiceListData.isDataNull()) {
            onSettingClick();
        }


    }

    @OnClick(R.id.view_setting)
    void onSettingClick() {
        ActivityTool.skipActivityForResult(mContext, SeverSettingActivity.class, REQUEST_CITY_CHOOSE);
    }

    void onServiceChoosed(LoginServiceListData data) {
        MyUtils.putSerciceData(data);
    }


    public static final int REQUEST_REGISTER = 11;
    private final int REQUEST_FOGET = 13;
    private final int REQUEST_CITY_CHOOSE = 14;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_FOGET:
                if (resultCode == Activity.RESULT_OK) {
                    eidt_user.setText(data.getStringExtra("name"));
                    edit_pwd.setText(data.getStringExtra("pass"));
                    doLogin();
                }
                break;
            case REQUEST_CITY_CHOOSE:
                break;
            default:
                break;
        }
    }


    @OnClick(R.id.btn_login)
    void login() {
        doLogin();
    }


    @OnClick(R.id.text_regist)
    void regist() {
        Intent intent = new Intent(this, RegistActivity.class);
        startActivityForResult(intent, REQUEST_REGISTER);
    }

    @OnClick(R.id.text_forgetpwd)
    void fogetpwd() {
//        Intent intent = new Intent(this, ForgetPwdActivity.class);
//        startActivityForResult(intent, REQUEST_FOGET);

        String[] items = new String[]{"0592-5302222","0592-5302219","0592-5302259"};

        QMUIDialog.CheckableDialogBuilder builder =  new QMUIDialog.CheckableDialogBuilder(mContext);
                builder .setCheckedIndex(0)
                .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                .setTitle("联系管理员")
                .addItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        builder.addAction("取消", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
            }
        });
        builder.addAction("拨号", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                String num = items[builder.getCheckedIndex()];
                IntentUtils.callToDial(mContext,num);
                dialog.dismiss();
            }
        });
        builder.create().show();

    }


    @BindView(R.id.img_check_usere)
    ImageView img_check_usere;
    @BindView(R.id.img_check_pwd)
    ImageView img_check_pwd;

    @OnClick(R.id.view_remember_user)
    void rememberUser() {
        MySharedPreferences msp = new MySharedPreferences(mContext);
        msp.putRememberUser(!msp.getRememberUser());
        if (!msp.getRememberUser()) {
            msp.putRememberPwd(false);
        }
        setCheckView();
    }

    @OnClick(R.id.view_remember_pwd)
    void rememberPwd() {
        MySharedPreferences msp = new MySharedPreferences(mContext);
        msp.putRememberPwd(!msp.getRememberPwd());
        if (msp.getRememberPwd()) {
            msp.putRememberUser(true);
        }
        setCheckView();

    }

    void setCheckView() {
        MySharedPreferences msp = new MySharedPreferences(mContext);

        img_check_usere.setImageResource(msp.getRememberUser() ? R.drawable.img_radio_select : R.drawable.img_radio_default);
        img_check_pwd.setImageResource(msp.getRememberPwd() ? R.drawable.img_radio_select : R.drawable.img_radio_default);
    }

    String userName, password;

    void doLogin() {

//        ActivityTool.skipActivity(mContext,HomeTabActivity.class);
//        finish();

        LogUtil.i("LoginServiceListData.isDataNull()-->" + (LoginServiceListData.isDataNull()));
        if (LoginServiceListData.isDataNull()) {
            onSettingClick();
            return;
        }


        userName = eidt_user.getText().toString();
        if (TextUtils.isEmpty(userName)) {
            showToast(R.string.user_user_empty);
            return;
        }


        password = edit_pwd.getText().toString();
        if (TextUtils.isEmpty(password)) {
            showToast(R.string.user_password_empty);
            return;
        }



        MyParams params = new MyParams();
        params.put("uno", userName);
        params.put("pwd",password);
        showProgress();
        MyHttpUtils.get(Constants.URL_LOGIN, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
//                BasisBean basisBean = (BasisBean) result;
                dismissProgress();
                LoginBean loginBean = (LoginBean) result;
                onLoginSuccess(loginBean);
            }

            @Override
            public void onFailure(int httpWhat, Object result) {
//                super.onFailure(httpWhat, result);
                if(result != null){
                    BasisBean basisBean = (BasisBean) result;
                        super.onFailure(httpWhat, result);
                }else {
                    super.onFailure(httpWhat, result);
                }
            }

            @Override
            public void onFinish(int httpWhat) {
                if(isFinishing())return;
                dismissProgress();
            }
        }, 0, LoginBean.class);

    }

    protected void onLoginSuccess(LoginBean loginBean) {
        showToast("登录成功");
        setResult(Activity.RESULT_OK);
        loginBean.save();
        MySharedPreferences mSp = new MySharedPreferences(this);
        if (mSp.getRememberUser()) {
            mSp.putUser(userName);
        } else {
            mSp.putUser("");
        }
        if (mSp.getRememberPwd()) {
            mSp.putPassword(password);
        } else {
            mSp.putPassword("");
        }
        if(LoginBean.getInstance().getRight() != null){
            ActivityTool.skipActivity(mContext, HomeTabActivity.class);
//                    TagAliasOperatorHelper.getInstance().setAlias(LoginBean.getInstance().getJpushAlias());
            finish();
        }else {
            ActivityTool.skipActivity(mContext, HomeTabActivity.class);
//            TagAliasOperatorHelper.getInstance().setAlias(LoginBean.getInstance().getJpushAlias());
            finish();
        }

    }

    private void onResultOk() {
        setResult(Activity.RESULT_OK);
        finish();
    }

}
